
var express = require('express');

var app = express();
app.configure(function() {
    app.use(express.bodyParser()); // used by POST (REST create) and PUT??
});

var fff = function(req, res) {
    res.setHeader('Content-Type', 'application/json');
    var obj = {'id':23};
    res.write(JSON.stringify(obj)); 
    res.end();
};
app.post('/acct', createAcct); // create
app.get('/acct/:b', getAcct); // read one
app.get('/acct', getAllAcct); // read all
app.put('/acct/:b', updateAcct); // update
app.delete('/acct/:b', deleteAcct); // delete

app.use(express.static(__dirname + '/er'));

app.listen(2323);

var ctr = 0;
var accts = {};
function createAcct(req, res) {
    res.setHeader('Content-Type', 'application/json');
    ctr++;
    var rb = req.body;
    console.log(JSON.stringify(rb)); 
    accts[ctr] = {'id':ctr, 'who':rb.who, 'age':rb.age, 'balance':rb.balance};
    res.write(JSON.stringify({'id':ctr})); 
    res.end();
}
function getAcct(req, res) {
    res.setHeader('Content-Type', 'application/json');
    var id = req.url.substr(6);
    var obj = accts[id];
    res.write(JSON.stringify(obj)); 
    res.end();
}
function getAllAcct(req,res) {
    res.setHeader('Content-Type', 'application/json');
    var acctArray = [];
    for (var id in accts) {
        acctArray.push(accts[id]);
    }
    res.write(JSON.stringify(acctArray)); 
    res.end();
}
function updateAcct(req, res) {
    res.setHeader('Content-Type', 'application/json');
    var id = req.url.substr(6);
    var rb = req.body;
    accts[id] = {'id':id , 'who':rb.who, 'age':rb.age, 'balance':rb.balance};
    res.write(JSON.stringify(accts[id])); 
    res.end();
}
function deleteAcct(req, res) {
    res.setHeader('Content-Type', 'application/json');
    var id = req.url.substr(6);
    res.write(JSON.stringify(delete accts[id])); 
    res.end();
}
/*
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    if (req.url.indexOf('/create/') > -1) {
        var obj = {'one':1, 'two':2};
        res.write(JSON.stringify(obj)); 
    }
    res.end();
}).listen(2323, "127.0.0.1");
console.log('Server running at http://127.0.0.1:2323/');
*/
